<!-- 数据匹配 -->
<template>
	<div class="data-matching">
		<el-form :inline="true" ref="queryRef" class="form-inline" label-position="right" :model="params" :rules="rules"
			label-width="200px">
			<div class="query-criteria">
				<el-row justify="center">
					<el-col :span="11">
						<el-form-item label="区域：" class="form-item" prop="province">
							<el-form-item prop="province" style="width: 120px; margin-right: 10px">
								<el-select v-model="params.province" placeholder="请选择省" @change="chooseProvince" clearable
									value-key="id">
									<el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item">
									</el-option>
								</el-select>
							</el-form-item>
							<el-form-item prop="city" style="width: 120px; margin-right: 10px">
								<el-select v-model="params.city" placeholder="请选择市" @change="chooseCity" clearable
									value-key="id">
									<el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item">
									</el-option>
								</el-select>
							</el-form-item>
							<el-form-item prop="county" style="width: 120px">
								<el-select v-model="params.county" placeholder="请选择县" @change="chooseCounty" clearable
									value-key="id">
									<el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item">
									</el-option>
								</el-select>
							</el-form-item>
						</el-form-item>
					</el-col>
					<el-col :span="11">
						<el-form-item label="结构类型：" prop="structureType">
							<el-col :span="12">
								<el-form-item prop="structureType">
									<el-select v-model="params.structureType" placeholder="请选择" class="form-select"
										@change="structureTypeChange" clearable>
										<el-option v-for="item in structureTypeOptions" :key="item.value"
											:label="item.label" :value="item.value">
										</el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="1" class="text-center">
								<span class="text-gray-500">-</span>
							</el-col>
							<el-col :span="11">
								<el-form-item prop="structureType1">
									<el-select v-model="params.structureType1" placeholder="请选择" class="form-select"
										clearable @change="structure1TypeChange">
										<el-option v-for="item in structureType1Options" :key="item.value"
											:label="item.label" :value="item.value">
										</el-option>
									</el-select>
								</el-form-item>
							</el-col>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row justify="center">
					<el-col :span="11">
						<el-form-item label="年代：" class="form-item" prop="years">
							<el-select v-model="params.years" placeholder="请选择" class="form-select" clearable>
								<el-option v-for="item in yearsOptions" :key="item.value" :label="item.label"
									:value="item.value">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="11">
						<el-form-item label="设防情况：" class="form-item" prop="fortification">
							<el-select v-model="params.fortification" placeholder="请选择" class="form-select" clearable>
								<el-option v-for="item in fortificationOptions" :key="item.value" :label="item.label"
									:value="item.value">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row justify="center">
					<el-col :span="11">
						<el-form-item label="用途：">
							<el-col :span="12">
								<el-form-item prop="use0">
									<el-select v-model="params.use0" placeholder="请选择" class="form-select"
										@change="useChange" clearable>
										<el-option v-for="item in useOptions" :key="item.value" :label="item.label"
											:value="item.value"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="1" class="text-center"><span class="text-gray-500">-</span></el-col>
							<el-col :span="11">
								<el-form-item prop="use1">
									<el-select v-model="params.use1" placeholder="请选择" class="form-select" clearable>
										<el-option v-for="item in useOptions1" :key="item.value" :label="item.label"
											:value="item.value"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
						</el-form-item>
					</el-col>
					<el-col :span="11">
						<el-form-item label="层数：" class="form-item" prop="cs">
							<el-select v-model="params.cs" placeholder="请选择" class="form-select" clearable :disabled="disabledcs">
								<el-option v-for="item in csOptions" :key="item.value" :label="item.label"
									:value="item.value">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row justify="end">
					<el-form-item class="bottom-button">
						<el-button type="primary" @click="onRest">重置</el-button>
					</el-form-item>
				</el-row>
			</div>
			<hr>
			<div class="table-wrapper">
				<el-form :inline="true" ref="tableForm1Ref" :model="yearsList" :rules="rules">
					<h4>年代：</h4>
					<el-table class="listTable" ref="yearTableRef" border :data="yearsList"
						:cell-style="{ border: '1px solid #e5ebf7' }"
						:header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
						<el-table-column prop="number" header-align="center" align="center" label="候选值" width="200">
							<template #default>面积比Ai</template>
						</el-table-column>
						<el-table-column v-for="(item, i) in yearsOptions" :key="i" :prop="`year${i}`" header-align="center"
							align="center" :label="item.label">
							<template #default="{ row, $index }">
								<el-form-item :prop="`${$index}.year${i}`" :rules="rules[`year${i}`]">
									<el-input type="number" v-model.number="row[`year${i}`]" :step="0.1" clearable
										:placeholder="`1/${yearsOptions.length}，请输入小数`" :min="0" :max="1"
										style="min-width: 200px;" :disabled="yearDisabled"></el-input>
								</el-form-item>
							</template>
						</el-table-column>
					</el-table>
				</el-form>
				<el-form :inline="true" ref="tableForm2Ref" :model="useList" :rules="rules">
					<h4>用途：</h4>
					<el-table class="listTable" ref="useTableRef" border :data="useList"
						:cell-style="{ border: '1px solid #e5ebf7' }"
						:header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
						<el-table-column prop="number" header-align="center" align="center" label="候选值" width="200">
							<template #default>面积比Bj</template>
						</el-table-column>
						<el-table-column v-for="(item, i) in useOptions" :key="i" :prop="`tableUse${i}`"
							header-align="center" align="center" :label="item.label">
							<template #default="{ row, $index }">
								<el-form-item :prop="`${$index}.tableUse${i}`" :rules="rules[`tableUse${i}`]">
									<el-input type="number" v-model.number="row[`tableUse${i}`]" :step="0.1" clearable
										:placeholder="`1/${useOptions.length}，请输入小数`" :min="0" :max="1"
										style="min-width: 200px;" :disabled="useDisabled"></el-input>
								</el-form-item>
							</template>
						</el-table-column>
					</el-table>
				</el-form>
				<el-form :inline="true" ref="tableForm3Ref" :model="csList" :rules="rules" v-if="!disabledcs">
					<h4>层数：</h4>
					<el-table class="listTable" ref="floorTableRef" border :data="csList"
						:cell-style="{ border: '1px solid #e5ebf7' }"
						:header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
						<el-table-column prop="number" header-align="center" align="center" label="候选值" width="200">
							<template #default>面积比Ck</template>
						</el-table-column>
						<el-table-column v-for="(item, i) in csOptions" :key="i" :prop="`floor${i}`" header-align="center"
							align="center" :label="item.label">
							<template #default="{ row, $index }">
								<el-form-item :prop="`${$index}.floor${i}`" :rules="rules[`floor${i}`]">
									<el-input type="number" v-model.number="row[`floor${i}`]" :step="0.1" clearable
										:placeholder="`1/${csOptions.length}，请输入小数`" :min="0" :max="1"
										style="min-width: 200px;" :disabled="csDisabled"></el-input>
								</el-form-item>
							</template>
						</el-table-column>
					</el-table>
				</el-form>
			</div>
			<el-row justify="end" style="margin-top: 18px;">
				<el-form-item class="bottom-button">
					<el-button type="primary" @click="onSearch">查询</el-button>
					<el-button type="primary" @click="onClean">全部清空</el-button>
				</el-form-item>
			</el-row>
		</el-form>
		<div v-show="showMatrix">
			<hr />
			<el-row justify="end" class="table-matrix">
				<el-button type="primary" @click="exportMatrixTableData">导出易损性矩阵</el-button>
			</el-row>
			<h4>地震易损性矩阵</h4>
			<el-table class="listTables" id="tableRef" ref="tableRef" border :data="tableDataMatrix" style="width: 100%"
				:cell-style="{ border: '1px solid #e5ebf7' }"
				:header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
				<el-table-column prop="damage" label="破坏程度" align="right" width="150">
					<el-table-column prop="intensity" label="烈度" width="150"></el-table-column>
				</el-table-column>
				<el-table-column header-align="center" align="center" label="基本完好" prop="bs">
					<template #default="scope">{{ scope.row.bs }}</template>
				</el-table-column>
				<el-table-column header-align="center" align="center" label="轻微破坏" prop="sl">
					<template #default="scope">{{ scope.row.sl }}</template>
				</el-table-column>
				<el-table-column header-align="center" align="center" label="中等破坏" prop="ml">
					<template #default="scope">{{ scope.row.ml }}</template>
				</el-table-column>
				<el-table-column header-align="center" align="center" label="严重破坏" prop="el">
					<template #default="scope">{{ scope.row.el }}</template>
				</el-table-column>
				<el-table-column header-align="center" align="center" label="倒塌" prop="c">
					<template #default="scope">{{ scope.row.c }}</template>
				</el-table-column>
			</el-table>
		</div>
		<el-dialog v-model="showDialog" :title="`共有${gridDataMatrix.length || 0}条结果符合条件，请选择一条结果查看：`">
			<el-table :data="gridDataMatrix" highlight-current-row @current-change="handleCurrentChange">
				<el-table-column type="select" width="55" />
				<el-table-column prop="name" label="矩阵名称" />
				<el-table-column prop="dateTime" label="生成时间" />
			</el-table>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="onClickConfirm">确定</el-button>
					<el-button @click="showDialog = false">取消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
import { reactive, toRefs, ref, unref } from "vue";
// 引入接口
import {
	queryMatrixListApi, //查询
} from "@/api/buildingVulnerAnalysis/buildingVulnerAnalysis.js";
import { getProvince, getChildArea } from "@/api/system/division";
// 公用方法
import { downloadFile } from '@/utils/ruoyi';
import { ElMessage, ElMessageBox } from 'element-plus'
// 前端导出excel文件
import { export_json_to_excel } from '@/vendor/Export2Excel';
// 状态管理模块
import useUserStore from "@/store/modules/user";
import useDictStore from "@/store/modules/dict";
// 获取pinia
const userStore = useUserStore();
const dictStore = useDictStore();
// 是否管理员
const isAdmin = computed(() => userStore.isAdmin || false);
// 用户名
const userName = computed(() => userStore.name || "");
// 所属机构名称
const orgName = computed(() => userStore.orgName || "");

// 获取当前实例
const { proxy } = getCurrentInstance();
// 全局路由对象
const router = useRouter();

// 显示弹出框
let showDialog = ref(false);
// 显示矩阵
let showMatrix = ref(false);

// 表单 年代用途层数 有值输入框禁用开关
let yearDisabled = ref(false)
let useDisabled = ref(false)
let csDisabled = ref(false)

const validateProvince = (rule, value, callback) => {
  if (value === ''||!value) {
    callback(new Error('请选择'))
  } else {
    if ((params.value.province == ''||!params.value.province)|| (params.value.city == ''||!params.value.city) || (params.value.county == ''||!params.value.county)) {
      callback(new Error('请选择'))
    }else{
		callback()
	}
  }
}
const validateStructureType = (rule, value, callback) => {
  if (value === ''||!value) {
    callback(new Error('请选择'))
  } else {
    if ((params.value.structureType == ''||!params.value.structureType)) {
      callback(new Error('请选择'))
    }else{
		if(structureType1Options.value&&structureType1Options.value.length>0){
			if(params.value.structureType1 == ''||!params.value.structureType1){
				callback(new Error('请选择'))
			}else{
				callback()
			}
		}else{
			callback()
		}
		
	}
  }
}

// 响应式对象
const data = reactive({
	// 表单参数
	params: {
		province: "", //省
		city: "", //市
		county: "", //县
		structureType: "", //结构类型
		structureType1: "",
		years: "", //年代
		fortification: "", //设防情况
		use0: "", //用途
		use1: "",
		cs: "", //层数
	},
	// 结构类型
	structureTypeOptions: dictStore.structureTypeOptions || [],
	structureType1Options: [],
	// 年代
	yearsOptions: dictStore.yearsOptions || [],
	// 设防情况
	fortificationOptions: dictStore.fortificationOptions || [],
	// 用途
	useOptions: dictStore.useOptions || [],
	useOptions1: [],
	// 层数
	csOptions: dictStore.csOptions || [],
	// 表单验证规则
	rules: {
		province: [
			{ required: true, message: '请选择', trigger: 'change',validator:validateProvince }
		],
		structureType: [
			{ required: true, message: '请选择', trigger: 'change',validator:validateStructureType }
		],
		// years: [
		// 	{ required: true, message: '请选择', trigger: 'change' }
		// ],
		fortification: [
			{ required: true, message: '请选择', trigger: 'change' }
		],

		year0: [
			// { required: true, message: '请输入', trigger: 'blur' },
			{ type: 'number', min: 0, max: 1, message: '请输入0-1之间的小数' }
		],
		year1: [
			// { required: true, message: '请输入', trigger: 'blur' },
			{ type: 'number', min: 0, max: 1, message: '请输入0-1之间的小数' }
		],
		year2: [
			// { required: true, message: '请输入', trigger: 'blur' },
			{ type: 'number', min: 0, max: 1, message: '请输入0-1之间的小数' }
		],
		year3: [
			// { required: true, message: '请输入', trigger: 'blur' },
			{ type: 'number', min: 0, max: 1, message: '请输入0-1之间的小数' }
		],
		year4: [
			// { required: true, message: '请输入', trigger: 'blur' },
			{ type: 'number', min: 0, max: 1, message: '请输入0-1之间的小数' }
		],
		year5: [
			// { required: true, message: '请输入', trigger: 'blur' },
			{ type: 'number', min: 0, max: 1, message: '请输入0-1之间的小数' }
		],

		tableUse0: [
			// { required: true, message: '请输入', trigger: 'blur' },
			{ type: 'number', min: 0, max: 1, message: '请输入0-1之间的小数' }
		],
		tableUse1: [
			// { required: true, message: '请输入', trigger: 'blur' },
			{ type: 'number', min: 0, max: 1, message: '请输入0-1之间的小数' }
		],
		tableUse2: [
			// { required: true, message: '请输入', trigger: 'blur' },
			{ type: 'number', min: 0, max: 1, message: '请输入0-1之间的小数' }
		],

		floor0: [
			// { required: true, message: '请输入', trigger: 'blur' },
			{ type: 'number', min: 0, max: 1, message: '请输入0-1之间的小数' }
		],
		floor1: [
			// { required: true, message: '请输入', trigger: 'blur' },
			{ type: 'number', min: 0, max: 1, message: '请输入0-1之间的小数' }
		],
		floor2: [
			// { required: true, message: '请输入', trigger: 'blur' },
			{ type: 'number', min: 0, max: 1, message: '请输入0-1之间的小数' }
		],
	},

	// 表格
	yearsList: [{}],
	useList: [{}],
	csList: [{}],
	// 矩阵表格
	currentRow: {},
	gridDataMatrix: [],
	tableDataMatrix: [],
	queryPagination: {
		pageNo: 1,
		pageSize: 10,
		total: 100,
	},
});
// 将一个响应式对象转换为一个普通对象
const {
	params,
	structureTypeOptions,
	structureType1Options,
	yearsOptions,
	fortificationOptions,
	useOptions,
	useOptions1,
	csOptions,
	rules,
	// 表格
	yearsList,
	useList,
	csList,
	// 矩阵表格
	currentRow,
	gridDataMatrix,
	tableDataMatrix,
	queryPagination,
} = toRefs(data);

watch(() => params.value, val => {
  if (val.years&&val.years!='') {
    yearDisabled.value = true;
	yearsList.value = [{}]
  }else{
	yearDisabled.value = false;
  }
  if (val.use0&&val.use0!='') {
    useDisabled.value = true;
	useList.value = [{}]
  }else{
	useDisabled.value = false;
  }
  if (val.cs&&val.cs!='') {
    csDisabled.value = true;
	csList.value = [{}]
  }else{
	csDisabled.value = false;
  }
}, { deep: true, immediate: true });

// 行政区划
const provinceData = ref([]); //省
const cityData = ref([]); //市
const areaData = ref([]); //区、县
/** 获取省列表 */
function getProvinceData() {
	getProvince().then((response) => {
		provinceData.value = response.data;
	});
}
// 选择省份
function chooseProvince(value) {
	params.value.city = null;
	params.value.county = null;
	params.value.province = value.name;
	cityData.value = [];
	areaData.value = [];
	getChildArea(value.id).then((response) => {
		cityData.value = response.data;
	});
}
// 选择城市
function chooseCity(value) {
	params.value.city = value.name;
	params.value.county = null;
	areaData.value = [];
	getChildArea(value.id).then((response) => {
		areaData.value = response.data;
	});
	proxy.$refs['queryRef'].validateField('province')
}
// 选择区县
function chooseCounty(value) {
	params.value.county = value.name;
	proxy.$refs['queryRef'].validateField('province')
}

// 以下结构对应全楼层
const arrStructure = ['钢筋混凝土结构', '钢结构', '组合结构'];
// 结构类型选择
const disabledcs = ref(false);
const structureTypeChange = (val) => {
	const structureTypes = structureTypeOptions.value.find(item => item.value === val);
	// 设置二级预选值
	if (structureTypes) {
		structureType1Options.value = structureTypes.children;
	}
	// 清空选中的二级候选值
	params.value.structureType1 = '';
	// 清空用途
	params.value.use0 = '';
	params.value.use1 = '';
	useOptions1.value = [];
	// 设防情况
	params.value.fortification = '';
	fortificationOptions.value = dictStore.fortificationOptions;
	// 年代
	yearsOptions.value = dictStore.yearsOptions;
	// 过滤楼层预选项
	if (val=='钢筋混凝土结构'||val=='钢结构') {
		csOptions.value = dictStore.csOptions;
		disabledcs.value = false;
		// 用途处理
		useOptions.value = dictStore.useOptions;
	} else if(val=='组合结构'){
		// 层数处理
		csOptions.value = dictStore.csOptions.filter((item, index) => index == 2);
		params.value.cs = ''
		disabledcs.value = false;
		// 用途处理
		useOptions.value = [
            {
                value: '第Ⅰ类',
                label: '第Ⅰ类',
                children: [
                    {
                        value: '住宅',
                        label: '住宅'
                    },
                    {
                        value: '公寓',
                        label: '公寓'
                    },
                    {
                        value: '学生和职工集体宿舍',
                        label: '学生和职工集体宿舍'
                    },
                    {
                        value: '宾馆',
                        label: '宾馆'
                    },
                    {
                        value: '招待所',
                        label: '招待所'
                    },
                    {
                        value: '其他人员居住场所',
                        label: '其他人员居住场所'
                    }
                ]
            },
            {
                value: '第Ⅱ类',
                label: '第Ⅱ类',
                children: [
                    {
                        value: '办公室',
                        label: '办公室'
                    },
                ]
            },
        ]
		// 设防情况
		fortificationOptions.value = dictStore.fortificationOptions.filter(item=>(item.value!='未设防'&&item.value!='自设防'));
	}else if(val=='砌体结构'){
		// 层数处理
		csOptions.value = dictStore.csOptions.filter((item, index) => index < 2);
		disabledcs.value = false;
		// 切换类型时，部分类型楼层没有就"9层以上"选项，则清空
		if (params.value.cs == '9层以上') {
			params.value.cs = ''
		}
		// 设防情况
		fortificationOptions.value = dictStore.fortificationOptions;
	}else{
		// 层数处理
		disabledcs.value = true;
		csOptions.value = [];
		params.value.cs = ''
		// 用途
		if(val=='土木结构'||val=='木结构'||val=='其他'){
			useOptions.value = [
            {
                value: '第Ⅰ类',
                label: '第Ⅰ类',
                children: [
                    {
                        value: '住宅',
                        label: '住宅'
                    },
                    {
                        value: '其他人员居住场所',
                        label: '其他人员居住场所'
                    }
                ]
            },
            {
                value: '第Ⅲ类',
                label: '第Ⅲ类',
                children: [
                    {
                        value: '除I、II类以外',
                        label: '除I、II类以外'
                    }
                ]
            }
        ]
		if(val=='土木结构'){
		// 设防情况
		fortificationOptions.value = dictStore.fortificationOptions.filter(item=>item.value=='未设防');
		yearsOptions.value = dictStore.yearsOptions.filter((item, index) => index < 4);
		// 切换类型时，年代--选项，则清空
		if (params.value.years == '2010-2016年'||params.value.years == '2016年以后') {
			params.value.years = ''
		}
		}else if(val=='其他'){
			fortificationOptions.value = dictStore.fortificationOptions.filter(item=>(item.value=='未设防'||item.value=='自设防'||item.value=='6度'));
		}
	}else{
			useOptions.value = [
            {
                value: '第Ⅱ类',
                label: '第Ⅱ类',
                children: [
                    {
                        value: '生产车间',
                        label: '生产车间'
                    },
                ]
            },
        ]
		}
	}
};
const structure1TypeChange = () =>{
	proxy.$refs['queryRef'].validateField('structureType')
}
// 用途选择
const useChange = (val) => {
	const use = useOptions.value.find((item) => item.value === val);
	if (use) {
		useOptions1.value = use.children;
	}
	// 清空选中的二级候选值
	params.value.use1 = '';
};

// 重置
const onRest = () => {
	// 清空表单
	proxy.resetForm("queryRef");
};
// 查询
const onSearch = () => {
	proxy.$refs['queryRef'].validate(async (valid, fields) => {
		if (valid) {
			let arrYears = [];
			// 年代，若表单没有选择则需要列表输入
			if (!params.value.years && yearsList.value) {
				// 表单验证
				const tableForm1Valid = proxy.$refs['tableForm1Ref'].validate(async (valid, fields) => { valid, fields });
				if (!tableForm1Valid) {
					return;
				}
				// 年代
				const cur = yearsList.value[0];
				let arr = [];
				if (cur) {
					arr = Object.values(cur);
				}
				// 没有值的部分，均分补足，总比为100%
				if (arr.length < 6) {
					let sum = 0;
					if (arr.length) {
						sum = arr.reduce((prev, next) => {
							return Number(prev || 0) + Number(next || 0);
						})
					}
					// 判断差值并取平均
					let diffAverage = null;
					if(params.value.structureType=='土木结构'){
						const flag = (!cur.year0||cur.year0 == '0')&&(!cur.year0||cur.year1 == '0')&&(!cur.year2||cur.year2 == '0')&&(!cur.year3||cur.year3 == '0')
						if (sum == 1||flag) {
							diffAverage = Number(Number((1 - sum) / (4 - arr.length)).toFixed(10));
							arrYears = [
								cur.year0 || cur.year0 == '0' ? cur.year0 : diffAverage,
								cur.year1 || cur.year1 == '0' ? cur.year1 : diffAverage,
								cur.year2 || cur.year2 == '0' ? cur.year2 : diffAverage,
								cur.year3 || cur.year3 == '0' ? cur.year3 : diffAverage,
								// cur.year4 || cur.year4 == '0' ? cur.year4 : diffAverage,
								// cur.year5 || cur.year5 == '0' ? cur.year5 : diffAverage,
							]
						} else {
							proxy.$modal.msgWarning("输入的年代面积比Ai之和不等于100%，请检查输入占比值！");
							return;
						}
					}else{
						const flag = (!cur.year0||cur.year0 == '0')&&(!cur.year0||cur.year1 == '0')&&(!cur.year2||cur.year2 == '0')&&(!cur.year3||cur.year3 == '0')&&(!cur.year4||cur.year4 == '0')&&(!cur.year5||cur.year5 == '0')
						if (sum == 1||flag) {
							diffAverage = Number(Number((1 - sum) / (6 - arr.length)).toFixed(10));
							arrYears = [
								cur.year0 || cur.year0 == '0' ? cur.year0 : diffAverage,
								cur.year1 || cur.year1 == '0' ? cur.year1 : diffAverage,
								cur.year2 || cur.year2 == '0' ? cur.year2 : diffAverage,
								cur.year3 || cur.year3 == '0' ? cur.year3 : diffAverage,
								cur.year4 || cur.year4 == '0' ? cur.year4 : diffAverage,
								cur.year5 || cur.year5 == '0' ? cur.year5 : diffAverage,
							]
						} else {
							proxy.$modal.msgWarning("输入的年代面积比Ai之和不等于100%，请检查输入占比值！");
							return;
						}
					}
				} else {
					if(params.value.structureType=='土木结构'){
						arrYears = [
							cur.year0 || 0,
							cur.year1 || 0,
							cur.year2 || 0,
							cur.year3 || 0,
							// cur.year4 || 0,
							// cur.year5 || 0,
						]
					}else{
						arrYears = [
							cur.year0 || 0,
							cur.year1 || 0,
							cur.year2 || 0,
							cur.year3 || 0,
							cur.year4 || 0,
							cur.year5 || 0,
						]
					}
				}
			} else {
				proxy.resetForm("tableForm1Ref");
			}

			let arrUse = [];
			// 用途，若表单没有选择则需要列表输入
			if (!params.value.use0 && useList.value) {
				// 表单验证
				const tableForm2Valid = proxy.$refs['tableForm2Ref'].validate(async (valid, fields) => { valid, fields });
				if (!tableForm2Valid) {
					return;
				}
			// 用途
			const cur = useList.value[0];
				let arr = [];
				if (cur) {
					arr = Object.values(cur);
				}
				// 组合结构
				if(params.value.structureType=='组合结构'||params.value.structureType=='土木结构'||params.value.structureType=='木结构'||params.value.structureType=='其他'){
					// 用途可输入数量
					const useLen0 = useOptions.value[0].children.length;
					const useLen1 = useOptions.value[1].children.length;
					const useLen = useLen0 + useLen1;
					let arrUse1 = [];
					let arrUse2 = [];
					const use0 = useList.value[0].tableUse0;
					const use1 = useList.value[0].tableUse1;
					let sum = 0;
					let len = useLen;
					if (use0 || use0 == '0') {
						const average0 = Number((use0 / useLen0).toFixed(10));
						for (let i = 0; i < useLen0; i++) {
							arrUse1.push(average0);
						}
						sum += Number(use0 || 0);
						len -= useLen0;
					}
					if (use1 || use1 == '0') {
						const average1 = Number((use1 / useLen1).toFixed(10));
						for (let i = 0; i < useLen1; i++) {
							arrUse2.push(average1);
						}
						sum += Number(use1 || 0);
						len -= useLen1;
					}
					// 判断差值并取平均
					let diffAverage = null;
					const flag = (!use0||use0=='0')&&(!use1||use1=='0')
					if (sum == 1||flag) {
						if (len > 0) {
							diffAverage = Number(Number((1 - sum) / len).toFixed(10));
							if (arrUse1.length == 0) {
								for (let i = 0; i < useLen0; i++) {
									arrUse1.push(diffAverage);
								}
							}
							if (arrUse2.length == 0) {
								for (let i = 0; i < useLen1; i++) {
									arrUse2.push(diffAverage);
								}
							}
						}
						arrUse = [
							...arrUse1,
							...arrUse2,
						]
					} else {
						proxy.$modal.msgWarning("输入的用途面积比Bj之和不等于100%，请检查输入占比值！");
						return;
					}
				}else if(params.value.structureType=='工业厂房'){
				// 用途可输入数量
					const useLen0 = useOptions.value[0].children.length;
					const useLen = useLen0;
					let arrUse1 = [];
					const use0 = useList.value[0].tableUse0;
					let sum = 0;
					let len = useLen;
					if (use0 || use0 == '0') {
						const average0 = Number((use0 / useLen0).toFixed(10));
						for (let i = 0; i < useLen0; i++) {
							arrUse1.push(average0);
						}
						sum += Number(use0 || 0);
						len -= useLen0;
					}
					// 判断差值并取平均
					let diffAverage = null;
					if (sum == 1||(!use0||use0=='0')) {
						if (len > 0) {
							diffAverage = Number(Number((1 - sum) / len).toFixed(10));
							if (arrUse1.length == 0) {
								for (let i = 0; i < useLen0; i++) {
									arrUse1.push(diffAverage);
								}
							}
						}
						arrUse = [
							...arrUse1,
						]
					} else {
						proxy.$modal.msgWarning("输入的用途面积比Bj之和不等于100%，请检查输入占比值！");
						return;
					}
				}else{
					// 用途可输入数量
					const useLen0 = useOptions.value[0].children.length;
					const useLen1 = useOptions.value[1].children.length;
					const useLen2 = useOptions.value[2].children.length;
					const useLen = useLen0 + useLen1 + useLen2;
					let arrUse1 = [];
					let arrUse2 = [];
					let arrUse3 = [];
					const use0 = useList.value[0].tableUse0;
					const use1 = useList.value[0].tableUse1;
					const use2 = useList.value[0].tableUse2;
					
					let sum = 0;
					let len = useLen;
					if (use0 || use0 == '0') {
						const average0 = Number((use0 / useLen0).toFixed(10));
						for (let i = 0; i < useLen0; i++) {
							arrUse1.push(average0);
						}
						sum += Number(use0 || 0);
						len -= useLen0;
					}
					if (use1 || use1 == '0') {
						const average1 = Number((use1 / useLen1).toFixed(10));
						for (let i = 0; i < useLen1; i++) {
							arrUse2.push(average1);
						}
						sum += Number(use1 || 0);
						len -= useLen1;
					}
					if (use2 || use2 == '0') {
						const average2 = Number((use2 / useLen2).toFixed(10));
						for (let i = 0; i < useLen2; i++) {
							arrUse3.push(average2);
						}
						sum += Number(use2 || 0);
						len -= useLen2;
					}
					// 判断差值并取平均
					let diffAverage = null;
					const falg = (!use0||use0=='0')&&(!use1||use1=='0')&&(!use2||use2=='0')
					if (sum == 1||falg) {
						if (len > 0) {
							diffAverage = Number(Number((1 - sum) / len).toFixed(10));
							if (arrUse1.length == 0) {
								for (let i = 0; i < useLen0; i++) {
									arrUse1.push(diffAverage);
								}
							}
							if (arrUse2.length == 0) {
								for (let i = 0; i < useLen1; i++) {
									arrUse2.push(diffAverage);
								}
							}
							if (arrUse3.length == 0) {
								for (let i = 0; i < useLen2; i++) {
									arrUse3.push(diffAverage);
								}
							}
						}
						arrUse = [
							...arrUse1,
							...arrUse2,
							...arrUse3,
						]
					} else {
						proxy.$modal.msgWarning("输入的用途面积比Bj之和不等于100%，请检查输入占比值！");
						return;
					}
				}
			} else {
				proxy.resetForm("tableForm2Ref");
			}

			let arrFloors = [];
			// 层数，若表单没有选择则需要列表输入
			if (!params.value.cs && csList.value && csOptions.value.length!=0) {
				// 表单验证
				const tableForm3Valid = proxy.$refs['tableForm3Ref'].validate(async (valid, fields) => { valid, fields });
				if (!tableForm3Valid) {
					return;
				}
				// 层数
				const cur = csList.value[0];
				let arr = [];
				if (cur) {
					arr = Object.values(cur);
				}
				// 层数可输入数量
				const csLen = csOptions.value.length;
				// 没有值的部分，均分补足，总比为100%
				if (arr.length <= csLen&& csLen<2) {
					let sum = 0;
					if (arr.length) {
						sum = arr.reduce((prev, next) => {
							return Number(prev || 0) + Number(next || 0);
						})
					}
					// 判断差值并取平均
					let diffAverage = null;
					if (sum == 1||(!cur.floor0 || cur.floor0 == '0' )) {
						diffAverage = Number(Number((1 - sum) / (csLen - arr.length)).toFixed(10));
						arrFloors = [
							cur.floor0 || cur.floor0 == '0' ? cur.floor0 : diffAverage,
							// cur.floor1 || cur.floor1 == '0' ? cur.floor1 : diffAverage,
						]
					} else {
						proxy.$modal.msgWarning("输入的层数面积比Ck之和不等于100%，请检查输入占比值！");
						return;
					}
				}else if(csLen>1){
					let sum = 0;
					if (arr.length) {
						sum = arr.reduce((prev, next) => {
							return Number(prev || 0) + Number(next || 0);
						})
					}
					// 判断差值并取平均
					let diffAverage = null;
					const flag =csLen==2? (!cur.floor0||cur.floor0 == '0')&&(!cur.floor1||cur.floor1 == '0'):(!cur.floor0||cur.floor0 == '0')&&(!cur.floor1||cur.floor1 == '0')&&(!cur.floor2||cur.floor2 == '0')
					if (sum == 1||flag) {
						diffAverage = Number(Number((1 - sum) / (csLen - arr.length)).toFixed(10));
						arrFloors = [
							cur.floor0 || cur.floor0 == '0' ? cur.floor0 : diffAverage,
							cur.floor1 || cur.floor1 == '0' ? cur.floor1 : diffAverage,
						]
						// 有9层以上
						if (csLen == 3) {
							arrFloors.push(cur.floor2 || cur.floor2 == '0' ? cur.floor2 : diffAverage);
						}
					} else {
						proxy.$modal.msgWarning("输入的层数面积比Ck之和不等于100%，请检查输入占比值！");
						return;
					}					
				} else {
					arrFloors = [
						cur.floor0 || 0,
						cur.floor1 || 0,
					]
					// 有9层以上
					if (csLen == 3) {
						arrFloors.push(cur.floor2 || 0);
					}
				}
			} else {
				proxy.resetForm("tableForm3Ref");
			}
			queryMatrixListApi({
					// 基础信息
					...params.value,
					// 年份列表
					yearsList: arrYears,
					// 用途列表
					useList: arrUse,
					// 层数列表
					csList: arrFloors
				}).then((res) => {
					const { code, data } = res;
					if (code === 200 && data) {
						// 根据查询情况设置矩阵表格
						setMatrixTableData(data);
					}
				}).catch(err => {
					console.log(err.message);
				});

		}
	});
};
// 全部清空
const onClean = () => {
	// 清空表单
	proxy.resetForm("queryRef");
	// 清空表格
	yearsList.value = [{}];
	useList.value = [{}];
	csList.value = [{}];
	tableDataMatrix.value = [];
};

// 根据查询情况设置矩阵表格
function setMatrixTableData(data) {
	// 只有一个矩阵则直接返回并显示
	if (data.hasOwnProperty('countValue')) {
		// 设置矩阵数据
		setMatrixData(data.countValue);
		// 显示矩阵
		showMatrix.value = true;
	}
	// 若有多个矩阵，则放回多个，需要弹框选择
	else {
		//循环遍历之前加上非空判断
		gridDataMatrix.value = [];
		const arr = [];
		for (const key in data) {
			if (key && data[key]) {
				// 编号和时间
				const array = key.split('_');
				arr.push({
					number: key,
					name: `编号${array[0] || key}的易损性矩阵`,
					list: data[key] || [],
					dateTime: array[1] || ''
				});
			}
		}
		if (arr && arr.length) {
			gridDataMatrix.value = arr;
			// 显示弹出框
			showDialog.value = true;
		} else {
			proxy.$modal.msgWarning('没有符合条件的矩阵！');
		}
	}
}
// 弹出框表格选中行事件
function handleCurrentChange(val) {
	currentRow.value = val;
}
// 弹出框确定按钮事件
function onClickConfirm() {
	if (currentRow.value && currentRow.value.number) {
		// 设置矩阵数据
		setMatrixData(currentRow.value.list);
		showMatrix.value = true;
		showDialog.value = false;
	} else {
		proxy.$modal.msgWarning('请选择矩阵！');
		return false;
	}
}
// 设置矩阵数据
function setMatrixData(arr) {
	if (arr && arr.length) {
		// 结果列表
		const arrResult = [];
		// 烈度列表
		const arrIntensity = [];
		// 当前行数据
		let curRow = {};
		// 先按烈度排序再处理
		arr.sort((a, b) => {
			return parseInt(a.intensity) < parseInt(b.intensity) ? -1 : 1;
		}).map(item => {
			if (!arrIntensity.includes(item.intensity)) {
				arrIntensity.push(item.intensity);
				curRow = { intensity: item.intensity };
				arrResult.push(curRow);
			}
			switch (item.damage) {
				case '基本完好':
					curRow.bs = item.rate;
					curRow.damageBs = item.damage;
					break;
				case '轻微破坏':
					curRow.sl = item.rate;
					curRow.damageSl = item.damage;
					break;
				case '中等破坏':
					curRow.ml = item.rate;
					curRow.damageMl = item.damage;
					break;
				case '严重破坏':
					curRow.el = item.rate;
					curRow.damageEl = item.damage;
					break;
				case '倒塌':
					curRow.c = item.rate;
					curRow.damageC = item.damage;
					break;
				default:
					break;
			}
		})
		tableDataMatrix.value = arrResult;
	} else {
		tableDataMatrix.value = [];
	}
}
// 导出矩阵列表数据
function exportMatrixTableData() {
	if (tableDataMatrix.value && tableDataMatrix.value.length) {
		// 设置导出数据格式并导出
		const arrData = [];
		tableDataMatrix.value.map(item => {
			arrData.push([item.intensity, item.bs, item.sl, item.ml, item.el, item.c]);
		});
		export_json_to_excel({
			// 表头
			header: ['烈度', '基本完好', '轻微破坏', '中等破坏', '严重破坏', '倒塌'],
			data: arrData,
			filename: '易损性矩阵数据', //文件名
			autoWidth: true,
			bookType: 'xlsx',
		});

		// // 获取矩阵表格的number字段
		// const arrNumbers = tableDataMatrix.value.map(item => item.number);
		// // 自定义下载
		// // 逗号隔开的number值
		// exportMatrixDataApi({
		// 	numbers: arrNumbers.join(','),
		// 	type: 3 // 震害数据1,预测数据2,筛选数据3
		// }).then(res => {
		// 	if (res) {
		// 		downloadFile(res, '易损性矩阵数据.xlsx');
		// 	} else {
		// 		proxy.$modal.msgError('导出易损性矩阵数据失败！');
		// 	}
		// }).catch(err => {
		// 	proxy.$modal.msgError(err || '导出易损性矩阵数据失败！');
		// });
	} else {
		proxy.$modal.msgWarning('没有矩阵数据，无法导出！');
	}
}

// 挂载
onMounted(() => {
	// 获取省份数据
	getProvinceData();
});
</script>

<style lang="scss" scoped>
.data-matching {
	.form-inline {
		.el-form-item {
			margin-right: 0;
		}
	}

	:deep(.el-dialog) {
		.el-dialog__body {
			padding: 20px;

			.el-table {
				width: 100%;

				// 表格行选中效果
				// .current-row {
				// 	background-color: var(--el-table-tr-bg-color);
				// }
			}
		}
	}

	.table-matrix {
		margin-top: 18px;
	}
}
</style>